package org.weso.lodin.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.weso.lodin.to.CountryTO;
import org.weso.lodin.utils.POIUtils;

public class CountryDAOImpl implements CountryDAO{

	private static final String COUNTRIES_SHEET_NAME = "COUNTRIES";
	protected Logger logger = Logger.getLogger(CountryDAOImpl.class);
	public List<CountryTO> countryTOs;
	
	public CountryDAOImpl(InputStream data){
		this.countryTOs = load(data);
	}
	
	private List<CountryTO> load(InputStream data) {
		List<CountryTO> loadingCountryTOs = new LinkedList<CountryTO>();
		try{
			HSSFWorkbook wb = new HSSFWorkbook(data);
			FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
			HSSFSheet sheet = wb.getSheet(COUNTRIES_SHEET_NAME);
			int rows = sheet.getPhysicalNumberOfRows();
			for (int r = 1; r < rows; r++) {
				HSSFRow row = sheet.getRow(r);
				if (row == null) {
					continue;
				}
				CountryTO country = new CountryTO();
				country.setCode(POIUtils.extractValue(row.getCell(2), evaluator));
				country.setIso2(POIUtils.extractValue(row.getCell(1), evaluator));
				country.setName(POIUtils.extractValue(row.getCell(0), evaluator));
				logger.debug(country);
				loadingCountryTOs.add(country);
				}
		}catch(IOException e){
			e.printStackTrace();
		}
		return loadingCountryTOs;
	}


	public List<CountryTO> getCountries() {
		return this.countryTOs;
	}

}
